// pages/pay/index.js

const app = getApp()
const dayjs = require('dayjs')
const {
  getTicketMessage,getBusinessTime
} = require("../../services/api/pay")
const {
  showToast
} = require('../../utils/util.js')
const {
  getAdvImg
} = require('../../services/api/common.js')

// 定义一个函数来解析并格式化日期字符串
function formatDateFromChineseString(dateString) {
  // 正则表达式匹配 YYYY年MM月
  const regex = /(\d{4})年(\d{2})月/;
  const match = dateString.match(regex);

  if (match) {
    const year = match[1];
    const month = match[2] - 1; // 月份从0开始，所以需要减1

    const months = [
      'January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'
    ];

    // 因为我们只有年和月，所以假设日期为1日
    // 如果需要具体日期，这里应该有一个额外的输入参数
    const day = 1; // 假设

    return `${months[month]} .${year}`; // 或者根据你的需求调整格式
  } else {
    return 'Invalid date format';
  }
}

Page({
  data: {
    activeDate: '',
    dateTicketNum: [],
    showdate: '2024年1月',
    datevalue: '2024-01-01 00:00:00',
    _showdate: '2024-01',
    days: [],
    selectDateIndex: -1,
    selectTimeIndex: -1,
    ticketInfoList: [],
    remainTicketNum: 0,
    userTicketNum: 0,
    aheadDay: 7,
    startDate: '',
    endDate: '',
    imgUrl: '/assets/tmps/pay-top.jpg',

  },
  onLoad() {
    app.initPageLang(this)
    let date = dayjs(new Date().getTime())
    this.setData({
      datevalue: date.format('YYYY-MM-DD HH:mm:ss'),
    
      _showdate: date.format('YYYY-MM')
    })
    if(this.data.language=='zh'){
      this.setData({
        showdate: date.format(`YYYY年MM月`),
      })
    }else{

      this.setData({
        showdate: formatDateFromChineseString(date.format(`YYYY年MM月`)),
      })
    }
    this.getAdvImg()
  },
  onShow() {
   
    this.initdays()
    this.loadData()
    // this.onShowDateAdd({currentTarget:{dataset:{type:'add'}}})
  },
  getAdvImg() {
    getAdvImg(9).then(res => {
      if (res.code === 0) {
        try {
          this.setData({
            imgUrl: res.info.advertInfoList[0].imgUrl
          })
          app.data.playImgUrlData = {
            imgUrl: res.info.advertInfoList[0].imgUrl,
            includeSubsets: res.info.advertInfoList[0].includeSubsets,
            advertisingPositionName: res.info.advertInfoList[0].advertisingPositionName,
            content: res.info.advertInfoList[0].content,
          }

        } catch (error) {

        }
      }
    })
  },

  loadData() {
    getTicketMessage().then(res => {
      if (res.code == 0) {
        this.setData({
          "dateTicketNum": res.info.dateTicketNum,
          ticketInfoList: res.info.ticketInfoList,
          userTicketNum: res.info.userTicketNum,
          aheadDay: res.info.aheadDay
        })
        this.initdays()
      }
    })
  },
  toLink() {
    app.toTinymceView(app.data.playImgUrlData)
  },
  onShowDateAdd({
    currentTarget: {
      dataset: {
        type,
        disabled
      }
    }
  }) {
    if (disabled) {
      return
    }
    if (type === 'add') {
      const date = dayjs(this.data.datevalue).add(1, 'month')
      this.data.datevalue = date.format('YYYY-MM-DD HH:mm:ss')
      this.setData({
        // showdate: date.format(`YYYY${this.data.$language.l28}M${this.data.$language.l29}`),
        _showdate: date.format('YYYY-MM')
      })
      console.log(this.data.language,"language");
      if(this.data.language=='zh'){
        this.setData({
          showdate: date.format(`YYYY年MM月`),
        })
      }else{
        this.setData({
          showdate: formatDateFromChineseString(date.format(`YYYY年MM月`)),
        })
      }
      this.initdays()
    } else if (type === 'reduce') {
      const date = dayjs(this.data.datevalue).add(-1, 'month')
      this.data.datevalue = date.format('YYYY-MM-DD HH:mm:ss')
      this.setData({
        // showdate: date.format(`YYYY${this.data.$language.l28}M${this.data.$language.l29}`),
        _showdate: date.format('YYYY-MM')
      })
      if(this.data.language=='zh'){
        this.setData({
          showdate: date.format(`YYYY年MM月`),
        })
      }else{
  
        this.setData({
          showdate: formatDateFromChineseString(date.format(`YYYY年MM月`)),
        })
      }
      this.initdays()
    }
  },
  initdays() {

    this.setData({
      weekdayMap: {
        1: app.data.$language.l31,
        2: app.data.$language.l32,
        3: app.data.$language.l33,
        4: app.data.$language.l34,
        5: app.data.$language.l35,
        6: app.data.$language.l36,
        0: app.data.$language.l37,
      }
    })
    const days = this.getdays(this.data.datevalue)
    this.setData({
      days
    })
    console.log(this.data.days, '22222222222222222222');
  },
   getDayOfWeek(dateString) {
    // 创建一个Date对象，假设日期字符串的格式是'YYYY-MM-DD'
    const date = new Date(dateString.replace(/-/g, '/')); // 替换-为/以兼容某些浏览器
    
    // getDay()方法返回的是0（星期日）到6（星期六）的数字
    // 在JavaScript中，不需要进行额外的调整，因为它已经符合题目要求（0代表星期日）
    return date.getDay();
},
  getdays(date) {
    let dayCount = dayjs(date).daysInMonth()
    console.log('dayCount', dayCount);
    console.log('date', date);
    // debugger
    let days = []
    console.log(dayCount,"dayCount");
    for (let i = 1; i <= dayCount; i++) {
      let item = this.data.dateTicketNum.find(e => e.date == (this.data._showdate + '-' + (i > 9 ? i : ('0' + i)))) || {}
     console.log(item,"item");
      let obj = {
        day: i,
        weekday: item.date?this.data.weekdayMap[this.getDayOfWeek(item.date)]:'',
        status: item.status,
        time: this.data._showdate + '-' + (i > 9 ? i : ('0' + i)),
        disabled: item.status == 0 && item.remainTicketNum > 0,
        remainTicketNum: item.remainTicketNum || 0
      }
      console.log(date,"23333");
      if (item.status != 0) { //闭馆
        obj.statusName = this.data.$language.l38
      } else if (item.remainTicketNum && item.remainTicketNum > 0) { //开馆
        obj.statusName = this.data.$language.l40
      } else { //已约满
        obj.statusName = this.data.$language.l39
      }
      days.push(obj)
    }

    let startDate = dayjs().format('YYYY-MM-DD')
    let endDate = dayjs().add(this.data.aheadDay, 'day').format('YYYY-MM-DD')
    console.log(days, 'daysdaysdaysdaysdaysdaysdays');
    this.setData({
      startDate,
      endDate
    })
    let flag = false
    days.forEach((e, i) => {
      console.log(e.time == startDate);
      if (e.time == startDate) {
        days = days.splice(i, this.data.aheadDay)
      }
      if (e.time == endDate) {
        flag = i
      }
    })
    if (flag) {
      days = days.slice(0, flag + 1)
    }
    return days
  },
  onSelectDateHandle({
    target: {
      dataset: {
        data,
        index
      }
    }
  }) {
    if (typeof index === 'number') {

      this.setData({
        selectDateIndex: index,
        activeDate: data.time,
        remainTicketNum: data.remainTicketNum
      })
    }
  },
  onSelectTimeHandle({
    target: {
      dataset: {
        value,
        index
      }
    }
  }) {
    if (typeof value === 'string') {
      this.setData({
        selectTimeIndex: index
      })
    }
  },
  async onConfirm() {
    //判断选中的日期是否是今天
    if(this.isToday(this.data.activeDate)){
      // 查询当天的营业时间
    let res =  await  getBusinessTime(this.data.activeDate)
    if(res.code==0){
      if(this.isCurrentTimeAfter(this.data.activeDate+' '+res.info.closeTime)){
        //超过当天开馆时间
        showToast(this.data.$language.l252)
       return
      }
    }
    }
    if (!this.data.activeDate) {
      showToast(this.data.$language.l41)
      return
    }
    const pages = getCurrentPages()
    const before = pages[pages.length - 2]
    if (before.route !== 'subpackages/pay/info/index') {
      wx.navigateTo({
        url: `/subpackages/pay/select/index?date=${this.data.activeDate}&userTicketNum=${this.data.userTicketNum}&remainTicketNum=${this.data.remainTicketNum}&info=${JSON.stringify(this.data.ticketInfoList)}&ticketDate=${this.data.activeDate}`,
      })
    } else {
      wx.navigateTo({
        url: '/subpackages/pay/info/index',
      })
    }
  },
  isToday(dateString) {
    // 定义一个函数来解析日期字符串为Date对象
    function parseDateString(str) {
      const [year, month, day] = str.split('-').map(Number);
      return new Date(year, month - 1, day); // 注意：月份在Date对象中是从0开始的
    }
   
    // 解析传入的日期字符串
    const inputDate = parseDateString(dateString);
   
    // 获取当前日期
    const currentDate = new Date();
   
    // 设置当前日期的时间部分为00:00:00，以便只比较日期部分
    currentDate.setHours(0, 0, 0, 0);
   
    // 同样设置输入日期的时间部分为00:00:00
    inputDate.setHours(0, 0, 0, 0);
   
    // 比较两个日期是否相等
    return inputDate.toISOString().startsWith(currentDate.toISOString().split('T')[0] + 'T');
    // 或者更简单地，比较它们的时间戳（但这种方法依赖于时区设置，可能不是最安全的）
    // return inputDate.getTime() === currentDate.getTime();
    // 由于我们已经将时间部分设置为0，所以更安全的比较是检查日期部分是否相同
  },
   isCurrentTimeAfter(dateTimeString) {
    // 解析传入的日期时间字符串为Date对象
    const inputDateTime = new Date(dateTimeString.replace(/-/g, '/')); // 替换-为/以兼容IE等老版本浏览器
  
    // 获取当前时间
    const currentTime = new Date();
  
    // 比较两个时间
    return currentTime > inputDateTime;
  }
})